package com.brotherly.framework.transaction;

import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import android.location.Location;

import com.brotherly.framework.event.EventService;
import com.brotherly.framework.service.ServiceHost;
import com.brotherly.geo.MapHelper;

public class LocationPacemaker implements Pacemaker, PacemakerFactory, com.brotherly.framework.event.EventListener
{
    protected PacemakerWatcher watcher;
    protected ServiceHost host;
    protected int stub;
    protected float distance;
    protected float prevLongitude, prevLatitude;

    public static final String type = "location";

    public LocationPacemaker(ServiceHost host)
    {
        this.host = host;
    }

    @Override
    public Pacemaker createInstance()
    {
        return new LocationPacemaker(host);
    }

    @Override
    public void active(Transaction transaction, PacemakerWatcher watcher)
    {
        this.distance = 500;
        this.prevLongitude = 0;
        this.prevLatitude = 0;

        this.watcher = watcher;

        Map<String, String> props = transaction.getPacemakerProps();
        if (props != null)
        {
            Number value = MapHelper.getNumber(props, "distance");
            if (value.intValue() != 0)
            {
                this.distance = value.floatValue();
            }
        }

        EventService service = (EventService) host.getService(EventService.description);
        stub = service.registerEventListener(TransactionConstant.event_location, this);
    }

    @Override
    public void inactive(Transaction transaction)
    {
        EventService service = (EventService) host.getService(EventService.description);
        service.unregisterEventListener(TransactionConstant.event_location, stub);
    }

    @Override
    public synchronized void onEvent(String id, Object param1, Object param2)
    {
        float dis[] = new float[]
        {
                0
        };

        try
        {
            JSONObject obj = (JSONObject) (new JSONParser().parse(param1.toString()));

            float longitude = MapHelper.getNumber(obj, "longitude").floatValue();
            float latitude = MapHelper.getNumber(obj, "latitude").floatValue();

            Location.distanceBetween(prevLatitude, prevLongitude, latitude, longitude, dis);

            if (dis[0] > this.distance)
            {
                prevLatitude = latitude;
                prevLongitude = longitude;

                if (watcher != null)
                    watcher.trigger();
            }
        }
        catch (Exception e)
        {}
    }
}
